package com.pms.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.pms.domain.AuthticateEntity;
import com.pms.domain.AuthticateResEntity;
import com.pms.domain.ReqInfo;
import com.pms.domain.UserData;
import com.pms.service.AuthenService;
import com.pms.service.UserDataService;
import com.pms.utils.CreateResponse;
import com.pms.utils.GetIPAddr;

/**
 * @ClassName: YxActivityController
 * @Description: 营销活动控制器
 * @author ZZW
 * @date 2016年12月6日 上午10:08:38
 * 
 */
@Controller
@RequestMapping("/userdata")
public class UserDataController {
	
//	private static final String XML_VIEW_NAME = "marshallingView";  // 返回XML格式的数据
	private static final String JSON_VIEW_NAME = "jsonView";        // 返回JSON格式的数据

	@Autowired
	private UserDataService userDataService;

	@Autowired
	private AuthenService authenService;

	/**
	 * 接受JSON串，解析并插入数据库
	 * 
	 * @param jsonStr
	 */
	@RequestMapping(value = "/insert.pfv", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public ModelAndView insertUserDatas(
			@RequestParam(value = "jsonStr") String jsonStr,
			@ModelAttribute ReqInfo reqInfo, HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		AuthticateEntity authenEnt = this.authenService.getAuthEntity(reqInfo
				.getAccount());
		String md5key = "";
		int status = -1;

		// 查询账号存在
		if (authenEnt != null) {
			md5key = authenEnt.getMd5key();
			String signstr = reqInfo.getAccount() + reqInfo.getTs()
					+ md5key;
			String md5Str = DigestUtils.md5Hex(signstr);
			// 验证签名
			if (!md5Str.equals(reqInfo.getSign())
					|| reqInfo.getAccount().equals("")
					|| reqInfo.getTs().equals("")) {
				status = -1;
			} else {
				reqInfo.setIpFrom((GetIPAddr.getIpAddr(req)));
				UserData userData = null;
				try {
					JSONObject jsonObj = JSONObject.fromObject(jsonStr);
					userData = new UserData();
					try {
						userData.setPhone(jsonObj.getJSONObject("dianhua")
								.getString("服务号码："));
						userData.setContent(new String(jsonStr.getBytes(),
								"UTF-8"));
						userData.setByw4gCus(jsonObj.getJSONObject(
								"banyewu").getString("4G有效客户："));
						userData.setBywCusIntegral(jsonObj.getJSONObject(
								"banyewu").getInt("用户积分："));
						userData.setBywCusStar(jsonObj.getJSONObject(
								"banyewu").getInt("客户星级："));
						userData.setBywHnwCus(jsonObj.getJSONObject(
								"banyewu").getString("是否惠农网客户："));
						userData.setBywJtw(jsonObj.getJSONObject("banyewu")
								.getString("是否家庭网："));
						userData.setBywSmzCus(jsonObj.getJSONObject(
								"banyewu").getString("实名制客户："));
						userData.setBywStock(jsonObj.getJSONObject(
								"banyewu").getString("存量2/3G客户："));
						userData.setMzdAverFlow(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三个月平均流量："));
						userData.setMzdAverPay(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三个月平均话费："));
						userData.setMzdCalls(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三个月话费："));
						userData.setMzdFlowPackage(jsonObj.getJSONObject(
								"maizhongduan").getDouble("订购流量包："));
						userData.setMzdLocalCall(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三月本地主叫本地时长："));
						userData.setMzdLocalLong(jsonObj.getJSONObject(
								"maizhongduan").getDouble(
								"近三月本地主叫国内长途时长："));
						userData.setMzdOverFlow(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三月超出套餐流量："));
						userData.setMzdRoamCall(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三月漫游主叫时长："));
						userData.setMzdRoamRec(jsonObj.getJSONObject(
								"maizhongduan").getDouble("近三月漫游接听时长："));
						userData.setMzdUsimCus(jsonObj.getJSONObject(
								"maizhongduan").getString("USIM卡客户："));
						userData.setZfwCusSta(jsonObj.getJSONObject(
								"zuofuwu").getString("用户状态："));
						userData.setZfwDate(jsonObj
								.getJSONObject("zuofuwu")
								.getString("开户日期："));
						userData.setTtcCostChange(jsonObj.getJSONObject(
								"tuitaocan").getDouble("预计消费变化："));
						userData.setTtcCostDown(jsonObj.getJSONObject(
								"tuitaocan").getDouble("预计消费下降："));
						userData.setTtcCurPackage(jsonObj.getJSONObject(
								"tuitaocan").getString("当前套餐："));
						userData.setTtcCusCost(jsonObj.getJSONObject(
								"tuitaocan").getDouble("用户消费："));
						userData.setTtcFlowUp(jsonObj.getJSONObject(
								"tuitaocan").getDouble("预计流量提升："));
						userData.setTtcOptSer(jsonObj.getJSONObject(
								"tuitaocan").getString("最优业务"));
						userData.setTtcOptTar(jsonObj.getJSONObject(
								"tuitaocan").getDouble("最优资费"));
						userData.setTtcRecPackage1(jsonObj.getJSONObject(
								"tuitaocan").getString("推荐套餐："));
						userData.setTtcRecPackage2(jsonObj.getJSONObject(
								"tuitaocan").getString("推荐套餐："));
						userData.setTtcVoUp(jsonObj.getJSONObject(
								"tuitaocan").getDouble("预计语音提升："));
						userDataService.insertUserData(userData);
						status = 0;
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
				} catch (JSONException e) {
					e.printStackTrace();
					status = 1;
				}
			}
		}
		AuthticateResEntity authticateResEntity = new AuthticateResEntity();
		if (status == 0) {
			authticateResEntity.setStatus("0");
			authticateResEntity.setStatusDesc("插入成功");
		} else if (status == -1) {
			authticateResEntity.setStatus("-1");
			authticateResEntity.setStatusDesc("sign效验失败");
		}else if(status == 1) {
			authticateResEntity.setStatus("1");
			authticateResEntity.setStatusDesc("插入失败");
		}
		return new ModelAndView(JSON_VIEW_NAME, "object", CreateResponse.createReponse(
				status, authticateResEntity));
	}
}
